from threading import  Thread

import requests

import export
from flask import Flask, render_template, request, redirect, send_from_directory
import subprocess
import os

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('mytrain.html')

@app.route('/train',methods=['POST'])
def train():
# 获取表单数据
    image_path = request.form['image_path']
    label_path = request.form['label_path']
    output_path = request.form['output_path']
# 构建训练命令
    train_command =  f'python train.py --data {image_path},{label_path} --weights {output_path}'

    try:
        t = Thread(target=run_training,args=(train_command,))
        t.daemon = True
        t.start()
        return f'Training started. Model will be saved to {output_path}'
    except subprocess.CalledProcessError as e:
        return f'An error occurred during training: {e}'

def run_training(train_command):
    subprocess.run(train_command,shell=True,check=True)


@app.route('/export')
#设置导出文件路径
def export_data():
    file_path ='out'
    return send_from_directory('data',filename='best1.pt',as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True, port=5001)